<%@ page language="java" import="java.util.*,com.yx.learn.domain.User" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">

		<title>角色管理</title>

		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
		<link rel="stylesheet" type="text/css" href="authority/css/easyui.css">
		<link rel="stylesheet" type="text/css" href="authority/css/icon.css">
		<link rel="stylesheet" type="text/css" href="authority/css/demo.css">
		<link rel="stylesheet" type="text/css" href="authority/css/dlg.css">
		<link rel="stylesheet" href="css/jquery.multiselect2side1.css" type="text/css" media="screen" />
		<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
		<script type="text/javascript" src="js/jquery.easyui.min.js"></script>
		<script type="text/javascript" src="js/jquery.multiselect2side.js"></script>
		<script type="text/javascript">
			var flag; //判断走的是保存还是修改方法
			$(function() {
				$('#tg').treegrid({
					loadMsg : '数据加载中请稍后……',
					url : 'RoleAction_findAllRole.action',
					lines : true,
					iconCls : 'icon-ok',
					rownumbers : true,
					animate : true,
					nowrap : false,
					collapsible : true,
					fitColumns : true,
					method : 'get',
					columns:[[
						{field:'roleNo',title:'角色编号',width:200} ,
						{field:'roleName',title:'角色名称',width:120} ,
						{field:'prid',title:'父ID',width:120} ,
						{field:'gen_time',title:'创建时间',width:120}, 
						{field:'memo',title:'描述',width:120},
						{field:'cid',title:'公司ID',width:120} 
					]],
					idField : 'id', //数据表格要有主键
					treeField : 'roleNo',//树形结构主键
					toolbar : '#tg_toolbar',//数据表工具栏
					onContextMenu : function(e, row) {
						e.preventDefault(); //屏蔽浏览器的菜单
						$(this).treegrid('unselectAll');//清除所有选中项
						$(this).treegrid('select', row.id);
						$('#op_menu').menu('show', {
							left : e.pageX,
							top : e.pageY
						});
					}
				});
		
				$('#op_menu').hide();
		
				$('#btncancer').click(function() {
					$('#tg_dd').dialog('close');
				});
				//表单确定提交按钮
				$('#btnsummit').click(function() {
								if ($('#myform').form('validate')) {
									if (flag == 'add') {
		
										var node = $('#tg').treegrid('getSelected');
										if (node == null) {
											//2、后台保存
										
												$.ajax({
													type : 'post',
													url : 'RoleAction_saveRole.action',
													cache : false,
													dataType : 'json',
													contentType : 'application/x-www-form-urlencoded; charset=utf-8',
													
													data : {
														prid : -1,
														roleNo : $('#myform').find('input[name=roleNo]').val(),
														roleName : $('#myform').find('input[name=roleName]').val(),
														memo : $('#myform').find('textarea[name=memo]').val(),
														cid : $('#myform').find('textarea[name=cid]').val()
													},
													success : function(result) {
														//关闭窗口
														$('#tg_dd').dialog('close');
														$('#tg').treegrid('reload');
														$.messager.show({
															title : '提示信息',
															msg :result.message,
															showType : 'fade',
															style : {
																right : '',
																bottom : ''
															}
														});
													},
													error : function(result) {
														$.meesager.show({
															title : '提示信息',
															msg : '添加角色失败',
															showType : 'fade',
															style : {
																right : '',
																bottom : ''
															}
														});
													}
		
												});
											
										} else {//node ！= null在某个父节点下添加
											
												//前台保存
												$('#tg').treegrid(
													'append',
													{
														parent : node.id,
														data : [ {
															name : $('#myform').find('input[name=name]').val(),
															paid : node.id,
															flag : $('#myform').find('input[name=flag]').val(),
															url : $('#myform').find('input[name=url]').val(),
															memo : $('#myform').find('textarea[name=memo]').val()
														} ]
													});
												//2、后台保存
		
												$.ajax({
													type : 'post',
													url : 'RoleAction_saveRole.action',
													cache : false,
													dataType : 'json',
													contentType : 'application/x-www-form-urlencoded; charset=utf-8',
													data : {
														roleNo : $('#myform').find('input[name=roleNo]').val(),
														prid : node.id,
														roleName : $('#myform').find('input[name=roleName]').val(),
														memo : $('#myform').find('textarea[name=memo]').val(),
														cid : $('#myform').find('textarea[name=cid]').val()

													},
													success : function(result) {
														$('#tg_dd').dialog(	'close');
														//刷新节点 : 刷新当前选中节点		
														$('#tg').treegrid(	'reload',node.id);
														$.messager.show({
															title : '提示信息',
															msg : result.message,
															showType : 'fade',
															style : {
																right : '',
																bottom : ''
															}
														});
													}
												});											
										}		
									} else {//不是 add
										
											//后台更新
											$.ajax({
												type : 'post',
												url : 'RoleAction_updateRole.action',
												cache : false,
												dataType : 'json',
												data : {
													id : $('#myform').find('input[name=id]').val(),
													roleNo : $('#myform').find('input[name=roleNo]').val(),
													roleName : $('#myform').find('input[name=roleName]').val(),
													memo : $('#myform').find('textarea[name=memo]').val(),
													cid : $('#myform').find('textarea[name=cid]').val()
												},
												success : function(result) {
													//刷新节点  :如果当前选中的节点是叶子节点的话,刷新该节点的父亲 ,如果不是叶子节点,刷新当前选中节点即可
													var node = $('#tg').treegrid('getSelected');
													var prid = $('#myform').find('input[name=prid]').val();
													if (prid != '-1') {
														var parent = $('#tg').treegrid('getParent',node.id);
														$('#tg').treegrid('reload',parent.id);
													} else {
														$('#tg').treegrid('reload');
													}
													$.messager.show({
														title : '提示信息',
														msg : result.message,
														showType : 'fade',
														style : {
															right : '',
															bottom : ''
														}
													});

												}
											});
											//3、关闭窗口
											$('#tg_dd').dialog('close');
										
										}
									} else {//表单验证不通过
												$.messager.show({
													title : '提示信息!',
													msg : '数据验证不通过,不能保存!',
													showType : 'fade',
													style : {
														right : '',
														bottom : ''
													}
												});
									}
		
								});	
			});
		
			function collapseAll(object) {
				object.treegrid('collapseAll');
			}
			function expandAll(object) {
				object.treegrid('expandAll');
			}
		
			function onAdd() {
				flag = 'add';
				//1、清空表单数据
				$('#myform').form('clear');
				$('#tg_dd').dialog('open');
			}
		
			function onUpdate() {
				flag = 'edit';
				var arr = $('#tg').datagrid('getSelections');
				if (arr.length != 1) {
					$('#dg').datagrid('unselectAll');
					$.messager.show({
						title : '提示信息!',
						msg : '只能选择单个角色编辑!',
						showType:'fade',
							style:{								
							right:'',
							bottom:''
						}
				});
				} else {
				$('#myform').form('clear');
				//2填充表单回显数据
				var node = $('#tg').treegrid('getSelected');
				$('#myform').form('load', {
					id : node.id,
					prid : node.prid,
					roleNo : node.roleNo,
					roleName : node.roleName,
					memo : node.memo,
					cid : node.cid
				});
				$('#tg_dd').dialog('open');
				}
			}
		
			function onDelete() {
			var arr = $('#tg').datagrid('getSelections');
			if (arr.length <= 0) {
				$.messager.show({
					title : '提示信息!',
					msg : '请选择角色!',
					showType:'fade',
						style:{								
						right:'',
						bottom:''
					}
				});
			} else {
				$.messager.confirm("提示信息", "确认删除?", function(r) {
					if (r) {
						// 1前台删除
						var node = $('#tg').treegrid('getSelected');
						$('#tg').treegrid('remove', node.id);
						// 2后台删除 
						$.post('RoleAction_deleteRole.action', {
							id : node.id
						}, function(result) {
							if (result) {
								$('#tg').treegrid('unselectAll');
								$('#tg').treegrid('reload');
								$.messager.show({
									title : '提示信息',
									msg : '删除角色成功!',
									showType : 'fade',
									style : {
										right : '',
										bottom : ''
									}
								});
							} else {
								$.messager.show({
									title : '提示信息',
									msg : '删除角色失败!',
									showType : 'fade',
									style : {
										right : '',
										bottom : ''
									}
								});
							}
		
						});
					} else {
						return;
					}
				});
				}
			}
		
			function onFind() {
				var roleNo = $('#findform').find('input[name=roleNo]').val();
				var roleName = $('#findform').find('input[name=roleName]').val();
		
				if (roleNo != "" || roleName != "") {
					$.post('RoleAction_findAllRole?find=find', {
						roleNo : roleNo,
						roleName : roleName
					}, function(result) {
						if (result != "") {
							$('#tg').treegrid('loadData', result);
						} else {
							$.messager.show({
								title : '提示信息',
								msg : '查询失败,或信息不存在',
								showType : 'fade',
								style : {
									right : '',
									bottom : ''
								}
							});
						}
					}, 'json');
				} else {
					alert("请输入查询条件");
					return;
				}
			}
			function clearForm() {
				$('#findform').form('clear');
				$('#tg').treegrid('reload');
		
			}
			function reject() {
				$('#tg').treegrid('unselectAll');
			}
			
			
			function onrole() {
				
				//先打开关联用户
				$('#connect_users').dialog('open');
				var rolenode = $('#tg').treegrid('getSelected');//获得选中的role
				
				if(rolenode!=null) {
					//对授权authority_aid渲染
					$(function(){
						console.info("当前选择的role是： " + rolenode.id);
						$('#authority_aid').tree({
							url:'authorityAction_getAllForTree.action',
							animate:true,
							checkbox:true ,
							cascadeCheck : false ,
						//	onlyLeafCheck: true ,
							onLoadSuccess:function(raw, data){
								
								//在全部权限里显示该角色的权限
									jQuery.getJSON('RoleAuthorityAction_getAllRoleAuthority.action', 
													{roleID:rolenode.id}, 
													function(json, textStatus) {
														  //遍历这个json取出 aid
														  $.each(json.rows, function(index, item) {
															  console.info("有的权限有 "+ item+" 个");
															  console.info("index = "+ index);
															  
															  var n = $("#authority_aid").tree('find',item.id);
									                            if(n){
									                                $("#authority_aid").tree('check',n.target);
									                            }
														
													      });
													});
									$('#authority_aid').tree('expandAll');
							}
						})
					});
					}
		var node = $('#tg').treegrid('getSelected');
		if(node!=null){
		
		
		$('#roleManage').dialog('open');
		$.post('UserRoleAction_getSelectUser.action', {
						id:node.id
					}, function(result) {
					if(result.length>2){
						$('#listKeyms2side__dx option').each(function (){
    						if($(this).text()!=null||$(this).text()!=""){
    							$(this).clone().appendTo($('#listKeyms2side__sx')).removeAttr("selected");
    							$(this).remove().appendTo($('#searchable')).removeAttr("selected");
 							}
 						});
						$.each(JSON.parse(result),function(i, obj){
                            $('#listKeyms2side__sx option').each(function (){ 
    							if($(this).val()==obj.uid){
    								$(this).remove();
    								$(this).remove().appendTo($('#listKeyms2side__dx')).removeAttr("selected");	
    								$('#searchable option[value="'+$(this).val()+'"]').eq(0).remove();
    								//$("#searchable").remove("<option value='"+$(this).val()+"'>'"+$(this).text()+"'<option>");
    								//$("#listKeyms2side__sx").empty();
 								}
 							}); 
 							
                         }); 
                    }else{
                    	$('#listKeyms2side__dx option').each(function (){
    						if($(this).text()!=null||$(this).text()!=""){
    							$(this).clone().appendTo($('#listKeyms2side__sx')).removeAttr("selected");
    							$(this).remove().appendTo($('#searchable')).removeAttr("selected");
 								//$("#searchable").append("<option value='"+$(this).val()+"'>'"+$(this).text()+"'<option>");  //添加一项option
 							}
 						});
                    }
		});
		
		}else{
			$.messager.show({
						title : '提示信息',
						msg : '请选择一个角色！',
						showType : 'fade',
						style : {
							right : '',
							bottom : ''
						}
					});
		}
	}

			//确定授权
			function a_certain_function() {
			
				var rolenode = $('#tg').treegrid('getSelected');//获得选中的role
				var aths = $('#authority_aid').tree('getChecked');//获得选中的权限
			
				if(aths != null){
				
					console.info("!!!aths.length = " + aths.length);
					
					var athsids = '';
					for ( var i = 0; i < aths.length-1; i++) {
						athsids += aths[i].id + ',';
					}
					athsids += aths[aths.length-1].id;
	
					//向数据库后台发送数据
					$.ajax({
						type : "post",
						url : 'RoleAuthorityAction_addRoleAuthority.action',
						dataType : 'json',
						cache : false,
						//	contentType: "charset=utf-8",
						data : {
							roleID : rolenode.id,
							authorityAid : athsids
					//		authorityListlength : aths.length
						},
	
						success : function(r) {
							console.info(rolenode.roleNo), console
									.info(aths.length), $.messager.show({
								title : '提示信息',
								msg : '操作成功!'
							});
							$('#roleManage').dialog('close');
						}
				});
				}

			}

			//取消授权，关闭授权窗口
			function a_cancel_function() {
				$('#roleManage').dialog('close');
			}
		$().ready(function() {
		$('#searchable').multiselect2side({
			search : "待选区-搜索：<img src='img/search.gif' />",
			selectedPosition : 'right',
			moveOptions : false,
			labelsx : '待选区',
			labeldx : '已选区',
			autoSortAvailable:true,
			autoSort:true 
		});	
	});
	
	//通过id保存关联用户
	function summitUserToRole(){
		
		var ids = '';
		$('#listKeyms2side__dx option').each(function (){ 
    		if (ids != '')
				ids += ',';
			ids += $(this).val();;
 		});
		
		var node = $('#tg').treegrid('getSelected');
		$.post('UserRoleAction_userToRole.action', {ids:ids,id:node.id},function(result){
		$('#roleManage').dialog('close');
			   if (result!="") {
					$('#tg').treegrid('loadData', result);
					$.messager.show({
						title : '提示信息',
						msg : '保存用户成功',
						showType : 'fade',
						style : {
							right : '',
							bottom : ''
						}
					});
				} else {
					$.messager.show({
						title : '提示信息',
						msg : '保存用户失败',
						showType : 'fade',
						style : {
							right : '',
							bottom : ''
						}
					});
				}
			}, 'json');
	}
	
		</script>
<s:head/>
	</head>
	<body >
		<div class="easyui-layout" data-options="fit:true,border:false" style="height: 500px;padding:20px">

			<div align="center">
				<form id="findform" action="">

					<table title="查询条件">
						<tr>
							<td>
								角色编号:
								<input type="text" name="roleNo" value="">
							</td>
							<td>
								角色名称:
								<input type="text" name="roleName" value="">
							</td>
							<td>
								<a id="btnfind" class="easyui-linkbutton"
									data-options="iconCls:'icon-search',plain:true"
									onclick="onFind()">查询</a>
								<a id="clearbtn" class="easyui-linkbutton"
									data-options="iconCls:'icon-clear',plain:true"
									onclick="clearForm()">清空</a>
							</td>
						</tr>

					</table>
				</form>
			</div>

			<table id="tg" title="角色信息" style="height:450px">
			<!-- <thead>
					<tr>
						
						<th data-options="field:'roleNo',width:120">
							角色编号
						</th>
						<th data-options="field:'roleName',width:120">
							角色名称
						</th>
						<th data-options="field:'prid',width:80,align:'center'">
							父ID
						</th>
						<th data-options="field:'gen_time',width:120">
							创建时间
						</th>
						<th data-options="field:'memo',width:120">
							描述
						</th>
						<th data-options="field:'cid',width:60">
							公司ID
						</th>
					</tr>
				</thead>
			 -->	
			</table>


			<div id="tg_toolbar" align="right" style="width: 100%">
				<a href="javascript:void(0)" class="easyui-linkbutton lb"
					onclick="expandAll($('#tg').treegrid('expandAll'))">展开全部</a>
				<a href="javascript:void(0)" class="easyui-linkbutton lb"
					onclick="collapseAll($('#tg').treegrid('collapseAll'))">关闭全部</a>
				<a href="javascript:void(0)" class="easyui-linkbutton "
					data-options="iconCls:'icon-add',plain:true" onclick="onrole()">角色授权</a>
				<a href="javascript:void(0)" class="easyui-linkbutton "
					data-options="iconCls:'icon-add',plain:true" onclick="onAdd()">增加</a>
				<a href="javascript:void(0)" class="easyui-linkbutton"
					data-options="iconCls:'icon-edit',plain:true" onclick="onUpdate()">编辑</a>
				<a href="javascript:void(0)" class="easyui-linkbutton"
					data-options="iconCls:'icon-remove',plain:true" onclick="onDelete()">删除</a>
				<a href="javascript:void(0)" class="easyui-linkbutton"
					data-options="iconCls:'icon-undo',plain:true" onclick="reject()">取消</a>
			</div>

			<div id="op_menu" class="easyui-menu" style="width: 120px;">
				<div onclick="onAdd()">
					添加
				</div>
				<div onclick="onUpdate()">
					修改
				</div>
				<div onclick="onDelete()">
					删除
				</div>
			</div>

			<!--添加弹出框  -->
			<div id="tg_dd" title="角色信息" class="easyui-dialog"
				data-options="closed:true,modal:true"
				 style="padding:10px;">				
				<form id="myform" action="" method="post">
					<input type="hidden" name="id" value="" />
					<input type="hidden" name="prid" value="" />
					<table>
						<tr>
							<td>
								角色编号:
							</td>
							<td>
								<input type="text" class="easyui-textbox" name="roleNo"
									data-options="required:true,missingMessage:'角色编号必填!'" value="">
							</td>
						</tr>
						<tr>
							<td>
								角色名称:
							</td>
							<td>
								<input type="text" class="easyui-textbox" name="roleName"
									data-options="required:true,missingMessage:'角色名称必填!'" value="">
							</td>
						</tr>
						<tr>
							<td>
								角色描述:
							</td>
							<td>
								<textarea name="memo" cols="16" rows="5"></textarea>
							</td>
						</tr>
						<tr>
							<td>
								公司ID:
							</td>
							<td>
								<input type="text" class="easyui-textbox" name="cid">
							</td>
						</tr>
						<tr>
							<td></td>
							<td>
								<a id="btnsummit" class="easyui-linkbutton">确定</a>
								&nbsp;&nbsp;&nbsp;&nbsp;
								<a id="btncancer" class="easyui-linkbutton">取消</a>
							</td>
						</tr>

					</table>

				</form>
			</div>
			
			<div id="roleManage" class="easyui-dialog" title="角色授权 "				
				align="center" data-options="closed:true,modal:true"
				style="width: 750px; height: 550px">
				
				<div class="easyui-tabs" style="width: 750px; height: 500px">
				
									<div title="关联用户" style="overflow:hidden;">
					<form id="frm">
						<select name="listKey" multiple="multiple" id="searchable">
									<s:iterator var="user" value="#session.listUser">
										<option value="${user.uid}">
											${user.employName}
										</option>
									</s:iterator>
								</select>
						<input type="button" value="保存" onclick="summitUserToRole()"/>
					</form>
				</div>
					
					<div id="authorize_div" title="授权"  style="padding: 10px">
							
							<div id="tg_toolbar" align="right" style="height:7%">
								<a href="javascript:void(0)" class="easyui-linkbutton lb"
									onclick="expandAll($('#authority_aid').tree('expandAll'))">展开全部</a>
								<a href="javascript:void(0)" class="easyui-linkbutton lb"
									onclick="collapseAll($('#authority_aid').tree('collapseAll'))">关闭全部</a>
							</div>
							
							<div >
								<ul id = "authority_aid" class="easyui-tree"></ul>
							</div>
							
							<div style="height:7%">
								<a href="javascript:void(0)" class="easyui-linkbutton lb"
									onclick="a_certain_function()">确定</a>
								<a href="javascript:void(0)" class="easyui-linkbutton lb"
									onclick="a_cancel_function()">取消</a>
							</div>
					
					</div>
				</div>
			</div>
		</div>
	</body>
</html>
